import React, { useState } from "react";
import { IQItem } from "./type";
import { IAddReqObj } from "./store";
import {
  CHAT_ACTION,
  extractMarkdownText,
  getChatItemContent,
} from "@/utils/chat";
import ChatTool from "./Tool";
import { remove } from "lodash";
import { IToFeedBackParams, handleFeedback } from "./services";
import { message } from "antd";

interface IActionProps {
  isLoading: boolean;
  overlayVisible: boolean;
  qList: Array<IQItem>;
  chatSourceMapRef: any;
  selectTalk: { id?: string; content?: string };
  loadingActionFb: () => void;
  setQList: (qList: Array<IQItem>) => void;
  updateChatSome: (
    id: string,
    content: Partial<IQItem>,
    list?: Array<IQItem> | null,
    checkTablePreview?: boolean
  ) => void;
  handle: (v?: string, addReqObj?: IAddReqObj) => void;
  setOverlayVisible: (target: boolean) => void;
}

function useAction(props: IActionProps) {
  const {
    isLoading,
    overlayVisible,
    chatSourceMapRef,
    qList,
    selectTalk,
    updateChatSome,
    handle,
    loadingActionFb,
    setQList,
    setOverlayVisible,
  } = props;

  // 当前展示的 log list
  const [showActionLogList, setShowActionLogList] = useState<string[]>([]);
  const [showActionFileList, setShowActionFileList] = useState<string[]>([]);

  /**
   * @description: 当前所有对话项 都不播放语音
   * @return {*}
   */
  const batchUpdateChatSomeSpeakingFalse = (updateList = false) => {
    let cChatList = [...qList].map((item) => {
      return {
        ...item,
        speaking: false,
      };
    });
    if (updateList) {
      setQList([...cChatList]);
    }
    return cChatList;
  };

  /**
   * @description: 重新加载回答
   * @param {*} fast ：是否快速加载
   * true: 快速加载: 直接删除最后一个回答 并且重新请求（数组不添加提问）
   * false: 正常加载 走重新提问流程
   * @return {*}
   */
  const reLoad = (contentItem: IQItem, fast = false) => {
    console.log("reLoad ", contentItem, fast);
    console.log("reLoad chatSourceMapRef.current", chatSourceMapRef.current);
    if (isLoading) {
      return loadingActionFb();
    }
    // 获取这个回答的  问题信息
    const reqInfo = chatSourceMapRef.current?.[contentItem?.parentMsgId] ?? {};
    const reqContent = reqInfo?.messageBody?.contents?.[0] ?? {};
    const parentMsgId = reqInfo?.parentMsgId ?? "";
    const msgId = reqInfo?.msgId ?? "";
    const scene = reqInfo?.scene ?? null;
    console.log("reLoad reqInfo", reqInfo);
    console.log("reLoad reqContent", reqContent);
    // return
    if (fast) {
      // ! 不会走这个分支 直接走else 加入新对话
      const cList = [...qList];
      const lastContent = cList.pop();
      console.log("lastContent", lastContent);
      setQList(cList);
      handle(reqContent?.content, {
        add: false,
        list: cList,
        parentMsgId: parentMsgId,
        msgId: msgId,
        scene: scene,
        action: CHAT_ACTION.variant,
      });
    } else {
      handle(reqContent?.content, {
        parentMsgId: parentMsgId,
        msgId: msgId,
        scene: scene,
        action: CHAT_ACTION.variant,
      });
    }
  };

  /**
   * @description: 语音播放
   * @param {IQItem} contentItem 对话项
   * @return {*}
   */
  const toPlay = (contentItem: IQItem) => {
    if (isLoading || overlayVisible) {
      return loadingActionFb();
    }
    ChatTool.onStopChatSpeak();

    let cQlist = batchUpdateChatSomeSpeakingFalse();
    let currentSpeakingType = contentItem?.speaking ?? false;
    console.log("cQlist", cQlist);

    if (currentSpeakingType) {
      // 已经在播放=> 暂停播放
      console.log("已经在播放需要=> 暂停播放");
      updateChatSome(
        contentItem?.id,
        {
          speaking: false,
        },
        cQlist
      );
      return;
    } else {
      updateChatSome(
        contentItem?.id,
        {
          speaking: true,
        },
        cQlist
      );
    }

    const content = getChatItemContent(contentItem);
    let speakText = content
      ? extractMarkdownText(content)
      : "未找到相关答案，您可以重新提问";
    // setOverlayVisible(true);

    message.info("加载中");
    ChatTool.onChatSpeak(speakText, {
      onEnded: () => {
        // Taro.hideLoading();
        // setOverlayVisible(false);
        updateChatSome(
          contentItem?.id,
          {
            speaking: false,
          },
          cQlist
        );
      },
    }).then(
      () => {
        // Taro.hideLoading();
        // setOverlayVisible(false);
      },
      () => {
        // setOverlayVisible(false);
        // Taro.hideLoading();

        updateChatSome(
          contentItem?.id,
          {
            speaking: false,
          },
          cQlist
        );
      }
    );
  };

  const toFeedback = async (params: IToFeedBackParams) => {
    const { id, feedback } = params;
    const dto = {
      ...params,
      sessionId: selectTalk.id,
    };
    const res = await handleFeedback(dto as any);
    console.log("toFeedback res", res);
    const { success, msg } = res;
    if (success) {
      message.success("评价成功");
      updateChatSome(id, {
        feedback,
      });
    } else {
      message.error(msg);
    }
  };

  /**
   * @description: 处理 展示 流程日志的对话切换操作
   * @param {string} id
   * @return {*}
   */
  const handleActionLogList = (id: string) => {
    let cList = [...showActionLogList];
    if (cList.includes(id)) {
      remove(cList, function (n) {
        return n === id;
      });
    } else {
      cList.push(id);
    }
    setShowActionLogList([...cList]);
  };

  const handleActionFileList = (id: string) => {
    let cList = [...showActionFileList];
    if (cList.includes(id)) {
      remove(cList, function (n) {
        return n === id;
      });
    } else {
      cList.push(id);
    }
    setShowActionFileList([...cList]);
  };

  return {
    showActionLogList,
    showActionFileList,
    reLoad,
    toPlay,
    toFeedback,
    handleActionLogList,
    handleActionFileList,
  };
}

export default useAction;
